<!--
  企业端-招聘管理-企业介绍
 -->
<template>
  <div class="app-container">
    <p class="selection-title">企业信息</p>
    <el-form
      ref="companyForm"
      :model="companyForm"
      :rules="rules"
      label-width="150px"
    >
      <el-form-item label="企业简称" prop="companyShortName">
        <el-input
          v-model="companyForm.companyShortName"
          type="text"
          :disabled="!isAdmin"
          maxlength="20"
          placeholder="请输入企业简称"
        />
      </el-form-item>
      <el-form-item label="企业logo" prop="companyLogo">
        <img
          v-if="!isAdmin"
          style="display: block; width: 146px; height: 146px"
          :src="companyForm.companyLogo"
          alt=""
        >
        <imageUpload v-else v-model="companyForm.companyLogo" />
      </el-form-item>
      <el-form-item label="所属行业" prop="industryType">
        <el-input
          v-if="!isAdmin"
          :disabled="!isAdmin"
          :value="companyForm.industryType"
        />
        <el-cascader
          v-else
          v-model="companyForm.industryType"
          :disabled="!isAdmin"
          :show-all-levels="false"
          :options="businessAreaData"
          @change="businessAreaChange"
        />
      </el-form-item>
      <p class="selection-title">关于我们</p>
      <el-form-item label="企业简介" prop="introduction">
        <el-input
          v-model="companyForm.introduction"
          :disabled="!isAdmin"
          placeholder="请输入企业简介"
          type="textarea"
          :autosize="{ minRows: 6, maxRows: 10 }"
          show-word-limit
          maxlength="20000"
        />
      </el-form-item>
      <el-form-item label="企业环境" prop="environment">
        <p>
          图片上传
          <el-tooltip
            class="item"
            effect="dark"
            content="图片最多上传20个,最大1.5M,建议图片保持统一尺寸"
            placement="top-start"
          >
            <i class="el-icon-warning-outline" style="margin: 10px" />
          </el-tooltip>
        </p>
        <imageUpload
          key="imageUpload"
          v-model="imgList"
          :unload-cover-style="{}"
          :disabled="!isAdmin"
          size-tips=",推荐图片比例为500:280"
          :limit="10"
        />
        <p>
          视频上传
          <el-tooltip
            class="item"
            effect="dark"
            content="视频最多上传20个,最大200M"
            placement="top-start"
          >
            <i class="el-icon-warning-outline" style="margin: 10px" />
          </el-tooltip>
        </p>
        <fileUpload
          key="fileUpload"
          v-model="videoList"
          :is-show-tip="false"
          :disabled="!isAdmin"
          :limit="20"
          :file-size="200"
          :only-video="true"
        />
      </el-form-item>
      <el-form-item label="企业地址" prop="companyAddress">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>填写企业地址</span>
            <el-button
              :disabled="!isAdmin"
              style="float: right; padding: 3px 0"
              type="text"
              @click="handleAddAddress()"
            >新增地址</el-button>
          </div>
          <div
            v-for="(item, ind) in companyForm.companyAddress"
            :key="'address' + ind"
            class="text item"
            style="margin-bottom: 14px"
          >
            <el-cascader
              v-model="item.provienAndcity"
              style="width: 200px"
              :show-all-levels="true"
              :options="provinceAndCityData"
              :disabled="!isAdmin"
              :props="{ value: 'label' }"
              placeholder="请选择企业所在省市"
              @change="handleCityChange(ind)"
            />
            <el-input
              v-model.trim="item.address"
              style="width: 50%; margin: 0 14px"
              maxlength="50"
              :disabled="!isAdmin"
              placeholder="请输入企业详细地址"
            />
            <el-button
              v-if="companyForm.companyAddress.length > 1 && isAdmin"
              type="text"
              style="color: red"
              @click="deleteAdd(ind)"
            >删除</el-button>
          </div>
        </el-card>
      </el-form-item>
      <el-form-item label="">
        <el-button
          v-if="isAdmin"
          type="primary"
          @click="submit"
        >修改并提交</el-button>
        <el-button v-if="isAdmin" @click="review">预览</el-button>
      </el-form-item>
    </el-form>
    <ReviewDialog ref="ReviewDialog" />
  </div>
</template>

<script>
import {
  updateCompanyInfo,
  getCompanyByLoginUser,
  getIsAdmin
} from '@/api/company-admin-api/hireManage/index.js'
import ImageUpload from './components/imageUpload'
import fileUpload from '@/components/FileUpload'
import businessAreaData from '@/utils/businessAreaData.js'
import { deepClone } from '@/utils/index'
import { provinceAndCityData } from '@/utils/frontDataDict.js'
import ReviewDialog from './components/recommendReivew.vue'
import moment from 'moment'

export default {
  name: 'Recommend',
  components: {
    ImageUpload,
    fileUpload,
    ReviewDialog
  },
  data() {
    const checkAddress = (rule, value, callback) => {
      const companyAddress = deepClone(this.companyForm.companyAddress)
      if (Array.isArray(companyAddress) && companyAddress.length) {
        const hasEmpty = companyAddress.some((item) => {
          if (!item.province || !item.city || !item.address) {
            return true
          }
        })
        if (hasEmpty) {
          return callback(new Error('企业地址不可为空'))
        } else {
          return callback()
        }
      } else {
        return callback(new Error('企业地址不可为空'))
      }
    }
    return {
      provinceAndCityData: provinceAndCityData,
      reviewCompanyDialog: false, // 企业预览
      // 企业行业类型数据，二级联动
      businessAreaData: businessAreaData,
      // 企业信息表
      companyForm: {
        companyShortName: '', // 企业名称
        companyLogo: '', // 企业logo
        industryType: '', // 行业类型
        introduction: '', // 企业简介
        environment: '', // 企业环境，图片、视频
        companyAddress: [
          {
            provienAndcity: [], // 省市
            province: '', // 省份
            city: '', // 城市
            address: '' // 地址
          }
        ] // 企业地址
      },
      videoList: '', // 企业环境视频
      imgList: '', // 企业环境图片
      // 表单校验
      rules: {
        companyShortName: [
          { required: true, message: '企业名称不能为空', trigger: 'blur' }
        ],
        companyLogo: [
          {
            required: true,
            message: '企业logo不能为空',
            trigger: 'change'
          }
        ],
        industryType: [
          {
            type: 'array',
            required: true,
            message: '行业类型不能为空',
            trigger: 'change'
          }
        ],
        introduction: [
          { required: true, message: '企业简介不能为空', trigger: 'blur' }
        ],
        environment: [
          {
            required: true,
            message: '企业环境不能为空',
            trigger: 'blur'
          }
        ],
        companyAddress: [
          {
            required: true,
            validator: checkAddress,
            type: 'array',
            trigger: 'blur'
          },
          {
            required: true,
            validator: checkAddress,
            type: 'array',
            trigger: 'change'
          }
        ]
      },
      isAdmin: false,
      // 接口返回完整公司数据
      fullCompanyInfo: {},
      companyInfo: null
    }
  },
  created() {
    this.getIsAdmin()
  },
  methods: {
    // 增加新地址
    handleAddAddress() {
      if (this.companyForm.companyAddress.length >= 10) {
        this.$message.warning('最多支持10个地址')
        return
      }
      const newAdd = {
        provienAndcity: [], // 省市
        province: '', // 省份
        city: '', // 城市
        address: '' // 地址
      }
      this.companyForm.companyAddress.push(newAdd)
    },
    deleteAdd(index) {
      this.companyForm.companyAddress.splice(index, 1)
    },
    // 地址省市变化,更新省、市字段
    handleCityChange(index) {
      const { provienAndcity } = this.companyForm.companyAddress[index]
      if (Array.isArray(provienAndcity) && provienAndcity.length === 2) {
        this.companyForm.companyAddress[index].province = provienAndcity[0]
        this.companyForm.companyAddress[index].city = provienAndcity[1]
      }
    },
    getIsAdmin() {
      getIsAdmin().then((res) => {
        if (res.code === 0 && res.data) {
          this.isAdmin = true
        }
        this.getData()
      })
    },
    // 预览企业
    reviewCompany() {
      this.reviewCompanyDialog = true
    },
    // 企业行业类型修改
    businessAreaChange(value) {
      this.companyForm.industryType = value
    },
    // 获取企业默认信息
    getData() {
      getCompanyByLoginUser().then((res) => {
        this.fullCompanyInfo = res.data
        // 获取企业地址
        try {
          this.fullCompanyInfo.companyAddress = JSON.parse(
            this.fullCompanyInfo.companyAddress
          )
          this.fullCompanyInfo.companyAddress =
            this.fullCompanyInfo.companyAddress.filter((item) => item.city)
        } catch (error) {
          this.fullCompanyInfo.companyAddress = [
            {
              provienAndcity: [], // 省市
              province: '', // 省份
              city: '', // 城市
              address: '' // 地址
            }
          ]
        }
        // 获取行业类型
        try {
          const industryType = JSON.parse(this.fullCompanyInfo.industryType)
          this.fullCompanyInfo.industryType = industryType
          this.fullCompanyInfo.industry = industryType
          if (!this.isAdmin) {
            this.fullCompanyInfo.industryType = industryType[1]
            this.fullCompanyInfo.industry = industryType[1]
          }
        } catch (error) {
          this.fullCompanyInfo.industryType = []
          this.fullCompanyInfo.industry = []
        }
        // 获取企业环境 视频、图片
        try {
          const environment = JSON.parse(this.fullCompanyInfo.environment)
          /**
           * 企业环境格式
           * {
                "videoList": [
                    {src:"https://demo-oss.oss-cn-beijing.aliyuncs.com/mp4/d6e7ec98e7184a04a135cdfe58d741a6.mp4", updateTime: ''}
                ],
                "imgList": [
                    {src:"https://demo-oss.oss-cn-beijing.aliyuncs.com/png/3c9d378d02704beca4dbd03121be6ddd.png", updateTime: ''}
                ]
            }
           */
          // 文件上传组件要求媒体格式是数组或逗号字符串，[a, b, c],'a,b,c' 这里为了组件回显，做了拼接操作
          if (
            Array.isArray(environment.videoList) &&
            environment.videoList.length &&
            environment.videoList[0]?.src
          ) {
            this.videoList = environment.videoList
              .map((item) => item.src)
              .join(',')
          } else {
            // hack 兼容老数据没有src的情况，后续更新了也不影响运行
            this.videoList = environment.videoList.join(',')
          }
          if (
            Array.isArray(environment.imgList) &&
            environment.imgList.length &&
            environment.imgList[0]?.src
          ) {
            this.imgList = environment.imgList
              .map((item) => item.src)
              .join(',')
          } else {
            // hack 兼容老数据没有src的情况，后续更新了也不影响运行
            this.imgList = environment.imgList.join(',')
          }
        } catch (error) {
          // 文件上传组件要求媒体格式是数组或逗号字符串，[a, b, c],'a,b,c'，支持空数组
          this.videoList = []
          this.imgList = []
        }
        Object.assign(this.companyForm, this.fullCompanyInfo)
        setTimeout(() => {
          !this.isAdmin && this.$refs.companyForm.clearValidate()
        }, 0)
      })
    },
    submit() {
      let companyForm = deepClone(this.companyForm)
      companyForm = Object.assign(this.fullCompanyInfo, companyForm)
      // 企业环境
      const environment = {
        videoList: [],
        imgList: []
      }
      this.imgList &&
        this.imgList.length &&
        this.imgList.split(',').map((item) => {
          environment.imgList.push({
            src: item,
            updateTime: moment().format('yyyy-MM-DD')
          })
        })
      this.videoList &&
        this.videoList.length &&
        this.videoList.split(',').map((item) => {
          environment.videoList.push({
            src: item,
            updateTime: moment().format('yyyy-MM-DD')
          })
        })
      // 企业环境，包含图片、视频
      companyForm.environment = JSON.stringify(environment)
      // this.companyForm.environment = JSON.stringify(environment)
      // 行业类型
      const industry = JSON.stringify(companyForm.industryType)
      companyForm.industryType = industry
      companyForm.industry = industry
      // 企业办公地址
      companyForm.companyAddress = JSON.stringify(companyForm.companyAddress)
      this.$refs.companyForm.validate((boo) => {
        if (boo) {
          updateCompanyInfo(companyForm).then((res) => {
            if (res.code === 0 && res.data) {
              this.$message.success('企业介绍信息提交成功，快去发布职位吧～')
              this.$router.push({ path: '/recruit/hireJob' })
            }
          })
        }
      })
    },
    review() {
      let companyForm = deepClone(this.companyForm)
      companyForm = Object.assign(this.fullCompanyInfo, companyForm)
      // 企业环境
      const environment = {
        videoList: [],
        imgList: []
      }
      this.imgList &&
        this.imgList.length &&
        this.imgList.split(',').map((item) => {
          environment.imgList.push({
            src: item,
            updateTime: moment().format('yyyy-MM-DD')
          })
        })
      this.videoList &&
        this.videoList.length &&
        this.videoList.split(',').map((item) => {
          environment.videoList.push({
            src: item,
            updateTime: moment().format('yyyy-MM-DD')
          })
        })
      // 企业环境，包含图片、视频
      companyForm.environment = JSON.stringify(environment)
      // this.companyForm.environment = JSON.stringify(environment)
      // 行业类型
      const industry = JSON.stringify(companyForm.industryType)
      companyForm.industryType = industry
      companyForm.industry = industry
      // 企业办公地址
      companyForm.companyAddress = JSON.stringify(companyForm.companyAddress)
      this.$refs.companyForm.validate((boo) => {
        if (boo) {
          this.$refs.ReviewDialog.open(companyForm)
        }
      })
    }
  }
}
</script>

<style lang="scss" scope>
.selection-title {
  font-weight: bold;
  font-size: 30px;
}
::v-deep .upload-image-com .el-upload {
  width: auto !important;
}
</style>
